////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.stock;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.adapter.StockSearchListItemAdapter;
import cc.telecomdigital.tdstock.adapter.StockSearchViewHolder;

/**
 * 
 * @author haibo
 * 
 *  for  searching on stock by name or code
 *
 */
public class StockSearchActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String				TAG					= StockSearchActivity.class.getSimpleName();
	private static final String				SEPARATOR				= "  ";
	private static final int					PAGE_SIZE				= 11;
	private static final String[]				SEARCH_STATES			= {
			"		搜尋完成", "		更多結果...", "		搜尋失敗"						};

	private Button							_toolBtnReturn;

	private EditText						_stock_search_box;
	private ListView						_search_result_list;

	private ArrayList<StockSearchViewHolder>	_list;
	private StockSearchListItemAdapter			_adapter;

	private SharedPreferences				_prefsStockCode;

	private static boolean					_isDataComeFromPaging	= false;

	private Button							_btnClear;
	private ImageView						_indicatorImgView;
	

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stock_search);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		/*_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);*/
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");
				// BMP Mode  by ouyangzhihui 2011-10-13
				Class<? extends Activity>_cls = CurrentStockInfoActivity.class;
				if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
				{
					_cls = BMPCurrentStockInfoActivity.class;
				}
				Intent intent = new Intent(getApplicationContext(), _cls);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(_cls, intent);
			}
		});

		_stock_search_box = (EditText) findViewById(R.id.stock_search_box);
		initSearchBox();
		_search_result_list = (ListView) findViewById(R.id.search_result_list);

		_list = new ArrayList<StockSearchViewHolder>();

		_adapter = new StockSearchListItemAdapter(LayoutInflater.from(this), _list);

		_search_result_list.setAdapter(_adapter);

		_search_result_list.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				//the first line is the title
				if (position >= 0 && _list.size() != position + 1
						&& position < _list.size() - 1)
				{
					String[] elements = _list.get(position).item.getText()
							.toString().split("[" + SEPARATOR + "]");
					if (elements == null
							|| !TextUtils.isDigitsOnly(elements[0]
									.trim()))
					{
						return;
					}
					String stockCode = String.valueOf(Integer
							.parseInt(elements[0].trim()));
					_prefsStockCode = getSharedPreferences(
							CommonDefn.SYSTEM_CURRENT_SETTING,
							Context.MODE_PRIVATE);
					_prefsStockCode.edit().putString(
							CommonDefn.PREFERENCE_STOCK_CODE, stockCode)
							.commit();
					// BMP Mode  by ouyangzhihui 2011-10-13
					Class<? extends Activity>_cls = CurrentStockInfoActivity.class;
					if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
					{
						_cls = BMPCurrentStockInfoActivity.class;
					}
					Intent intent = new Intent(getApplicationContext(), _cls);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

					SwitchForwardActivity(_cls, intent);
				}
				else if (_list.size() == position + 1
						&& _list.get(position).item.getText().equals(
								SEARCH_STATES[1]))
				{
					_isDataComeFromPaging = true;
					
					SendHttpRequest();
				}
			}
		});

		_stock_search_box.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void afterTextChanged(Editable s)
			{
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				_list.clear();
				//_stock_search_box.setBackgroundDrawable(s.toString().length() >= 1 ? _search_box_bg[1]  : _search_box_bg[0] );
				_btnClear.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
				_isDataComeFromPaging = false;

				SendHttpRequest();
			}
		});

		_stock_search_box.setOnKeyListener(new OnKeyListener()
		{
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (KeyEvent.KEYCODE_ENTER == keyCode
						|| KeyEvent.KEYCODE_ENTER == event.getKeyCode())
				{
					//---------------------- auto close the soft keyboard after finishing input.---------------------- 
					Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					InputMethodManager imm = (InputMethodManager) service;
					imm.hideSoftInputFromWindow(_stock_search_box
							.getWindowToken(), 0);
					//---------------------- auto close the soft keyboard after finishing input.---------------------- 

					return true;
				}
				return false;
			}
		});
		
		_stock_search_box.setOnClickListener( new OnClickListener(){

			@Override
			public void onClick(View v)
			{
				openSoftKeyboardIfNeed(_stock_search_box);
//				Toast.makeText(v.getContext(), "click works!", 1500).show();
			}
		});
	}

	private void initSearchBox()
	{
		//			_search_box_bg = new Drawable[2];
		//			_search_box_bg[0] = getResources().getDrawable(R.drawable.stock_search_type);
		//			_search_box_bg[1] = getResources().getDrawable(R.drawable.stock_search_clear);
		//		
		_indicatorImgView = (ImageView) findViewById(R.id.scrolling_anim);
		_indicatorImgView.setBackgroundResource(R.anim.scrolling);
		_btnClear = (Button) findViewById(R.id.btn_right);

		_btnClear.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				_stock_search_box.setText("");
			}
		});

		_indicatorImgView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				_stock_search_box.setText("");
			}
		});
	}

	@Override
	protected void onResume()
	{
		SetExectuHttpRequestOnResume(false);
		super.onResume();
		_search_result_list.invalidateViews();
//		updateLocalData();
	}

//	private void updateLocalData()
//	{
//		/*	ITDLApplication app = (ITDLApplication) getApplicationContext();
//			_itemCode = app.getString(CommonDefn.STOCK_DIARY_EDITING_ITEMCODE);
//			_isNewDiary =  app.getString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO) == null ||  Integer.parseInt(app.getString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO)) <1;
//			*/
//	}

	private synchronized void updateAdapter()
	{
		_stock_search_box.setEnabled(false);
		_search_result_list.setVisibility(View.GONE);
		_adapter.notifyDataSetChanged();
		_search_result_list.setVisibility(View.VISIBLE);
		_stock_search_box.setEnabled(true);
	}

	private String getLastStockCode()
	{
		String result = null;

		if (_list == null || _list.isEmpty() || _list.size() < 2)
		{
			return result;
		}

		{
			String lastItem = _list.get(_list.size() - 2).item.getText()
					.toString();
			String[] items = lastItem.split("[" + SEPARATOR + "]");

			if (items == null || !TextUtils.isDigitsOnly(items[0].trim()))
			{
				return result;
			}

			result = String.valueOf(Integer.parseInt(items[0].trim()));

		}

		return result;
	}

	class StartUpAnim extends TimerTask
	{

		public void run()
		{
			// Get the background, which has been compiled to an AnimationDrawable object.
			AnimationDrawable frameAnimation = (AnimationDrawable) _indicatorImgView
					.getBackground();
			// Start the animation (looped playback by default).
			frameAnimation.start();
		}
	}

	class StopAnim extends TimerTask
	{

		public void run()
		{
			// Get the background, which has been compiled to an AnimationDrawable object.
			AnimationDrawable frameAnimation = (AnimationDrawable) _indicatorImgView
					.getBackground();

			// stop the animation (looped playback by default).
			frameAnimation.stop();
		}
	}

	void doAnim(boolean isStart)
	{
		_indicatorImgView.setVisibility(isStart ? View.VISIBLE
				: View.INVISIBLE);

		if (isStart)
		{
			StartUpAnim mar = new StartUpAnim();
			Timer t = new Timer(false);
			t.schedule(mar, 100);

		}
		else
		{

			StopAnim mar2 = new StopAnim();
			Timer t2 = new Timer(false);
			t2.schedule(mar2, 100);

		}
	}
	
	
	
	private  void  openSoftKeyboardIfNeed(EditText current)
	{
	     	  Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	     	  	if(service != null)
	     	  	{
	     	  		InputMethodManager imm = (InputMethodManager) service;
	     	  		boolean result = imm.showSoftInput(current, InputMethodManager.SHOW_FORCED |  InputMethodManager.SHOW_IMPLICIT  );
	     	  		if(!result) {
	     	  			 try
							{
								imm.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
	     	  		}
	     	  		else {
	     	  		
	     	  		}
					
	     	  	}
	     	  	else {
	     	  		Toast.makeText(current.getContext(), "對不起, 沒能彈出軟鍵盤，請先按手機menu鍵，再點此輸入！", 1500).show();
	     	  	}
	}
	
	
	
	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return StockGroup.GetActivityGroupHostControl();
	}

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		String searchContent = _stock_search_box.getText().toString().trim();
		
		searchContent = StringUtils.preUrlEncode(searchContent);
		
		String iQueryName = StringUtils.isChineseCharacterExist(searchContent) ? URLEncoder.encode(URLEncoder.encode(searchContent.trim())) : searchContent.trim();
		
		String iLastCode = getLastStockCode();
		
		return HttpAppInfo.SendStockSearchRequest(actContext, iQueryName, iLastCode == null ? "" : iLastCode, this);
	}
	
	@Override
	protected void ShowHideDialog(H_CODE statusCode)
	{
		if(statusCode == H_CODE.NONE) 
			return;
		
		if (statusCode == H_CODE.OK || statusCode == H_CODE.SYSTEM_BUSY)
			doAnim(true);
		else 
			ShowMessageDialog(statusCode.ToString());
	}

	@Override
	public void H_UserClient_HttpRequest_Response(H_UserClient_HttpRequest_Result iResult)
	{
		doAnim(false);
		H_UserClient_HttpRequest_Response_Sub(iResult);
	}
	
	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if (iResult.MStatus.equals("0") == false)
		{
			// Prompt Error
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			updateData(iResult.contentStores, true);
			return;
		}
		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				updateData(iResult.contentStores, false);
			}
		};
		_messageHandler.post(runnable);
	}

	private void updateData(List<String[]> searchResult, boolean _isExistException)
	{
		try
		{
			if(_isExistException)
			{
				_list.clear();
				StockSearchViewHolder holder = new StockSearchViewHolder();
				holder.id = 0;
				holder.item =  new TextView(StockSearchActivity.this);
				holder.item.setText(SEARCH_STATES[2]);
				holder.searchState = 2;
				_list.add(holder);
				_isDataComeFromPaging = false;
				return;
			}
			
			TDStockLog.d(TAG, "List size=" + searchResult.size());
			if (!_isDataComeFromPaging)
			{
				_list.clear();
			}
			else if (!_list.isEmpty())
			{
				_list.remove(_list.size() - 1);
			}
	
			int index = 0;
			long id = _list.size();
			for (String[] array : searchResult)
			{
				if (array[0] == null || array.length < 2)
				{
					continue;
				}
	
				StockSearchViewHolder holder = new StockSearchViewHolder();
				holder.id = id + index;
				holder.item = new TextView(StockSearchActivity.this);
				holder.item.setText(array[0] + SEPARATOR + array[1]);
				_list.add(holder);
				index++;
			}
			TDStockLog.d(TAG, "added items=" + index);
	
			int recordSize = (searchResult == null || searchResult.isEmpty()) ? 0 : searchResult.size();
			TDStockLog.d(TAG, "recordSize=" + recordSize);
	
			switch (recordSize)
			{
				case 0:
				{
					_isDataComeFromPaging = false;
					for (StockSearchViewHolder holder : _list)
					{
						holder.searchState = 0; //update all search state;
					}
	
					StockSearchViewHolder holder = new StockSearchViewHolder();
					holder.id = id + (++index);
					holder.item = new TextView(StockSearchActivity.this);
					holder.item.setText(SEARCH_STATES[0]);
					holder.searchState = 0;
					_list.add(holder);
					index++;
					break;
				}
				case PAGE_SIZE:
				{
					//--------------------for sync with iphone side, to show 10 records only--------------------
					_list.remove(_list.size() - 1);
					//--------------------forsync with iphone side, to show 10 records only--------------------
	
					for (StockSearchViewHolder holder : _list)
					{
						holder.searchState = 0; //update all search state;
					}
	
					StockSearchViewHolder holder = new StockSearchViewHolder();
					holder.id = id + (++index);
					holder.item = new TextView(StockSearchActivity.this);
					holder.item.setText(SEARCH_STATES[1]);
					holder.searchState = 1;
					_list.add(holder);
	
					break;
				}
				default:
				{
					StockSearchViewHolder holder = new StockSearchViewHolder();
					holder.id = id + (++index);
					holder.item = new TextView(StockSearchActivity.this);
					holder.item.setText(SEARCH_STATES[0]);
					holder.searchState = 0;
					_list.add(holder);
					_isDataComeFromPaging = false;
				}
			}
	
			updateAdapter();
		}
		catch(Exception e)
		{
			TDStockLog.e(TAG, "update exception=>"+e.toString());
		}
	}
}
